package service

import (
    "context"
    "gitee.com/WisdomClassroom/CollegeStruct/glb"
    "gitee.com/WisdomClassroom/core"
    "gitee.com/WisdomClassroom/core/models"
    "gitee.com/WisdomClassroom/core/protobufs/v1/pb"
    "github.com/jinzhu/gorm"
)

func (s *Service) GetCollege(_ context.Context, in *pb.GetCollegeRequest) (*pb.GetCollegeResponse, error) {
    token := core.NewToken()
    err := token.UnpackToken(in.AuthToken, &core.FlagTokenCert)
    if err != nil {
        return &pb.GetCollegeResponse{Status: &pb.ResponseStatus{
            Code: pb.ResponseStatusCode_NotAuth, Error: err.Error(),
        },}, nil
    }

    if len(in.CollegeUUID) != 36 {
        return &pb.GetCollegeResponse{Status: &pb.ResponseStatus{Code: pb.ResponseStatusCode_OtherError,
            Message: "学院编号不正确",
        },}, nil
    }

    college := models.CollegeModel{
        Model: models.Model{
            UUID: in.CollegeUUID,
        },
    }
    err = glb.DB.Scopes(notDeleted).Where(&college).First(&college).Error
    if err == gorm.ErrRecordNotFound {
        return &pb.GetCollegeResponse{Status: &pb.ResponseStatus{Code: pb.ResponseStatusCode_OtherError,
            Message: "学院编号不存在",
        },}, nil
    } else if err != nil {
        glb.Logger.Error(err.Error())
        return getCollegeRespSvrErr, nil
    }

    var collegeManagerBinds []models.CollegeManagerBindModel
    err = glb.DB.Scopes(notDeleted).Where("college_uuid=?", in.CollegeUUID).Find(&collegeManagerBinds).Error
    if err != nil && err != gorm.ErrRecordNotFound {
        glb.Logger.Error(err.Error())
        return getCollegeRespSvrErr, nil
    }

    var managerUUIDs []string
    for _, model := range collegeManagerBinds {
        managerUUIDs = append(managerUUIDs, model.ManagerUUID)
    }
    return &pb.GetCollegeResponse{
        Status:      &pb.ResponseStatus{Code: pb.ResponseStatusCode_Suc},
        Name:        college.Name,
        Description: college.Description,
        ManagerUUID: managerUUIDs,
    }, nil
}
